<?php
// +----------------------------------------------------------------------
// | INPHP
// | Copyright (c) 2023 https://inphp.cc All rights reserved.
// | Licensed ( https://opensource.org/licenses/MIT )
// | Author: 幺月儿(https://gitee.com/lulanyin) Email: inphp@qq.com
// +----------------------------------------------------------------------
// | 后台授权，使用后台配置的超级管理员账户和密码
// | 有IP超时限制
// +----------------------------------------------------------------------
namespace app\admin\http\api;

use Inphp\Core\Config;
use Inphp\Core\Db\Redis;
use Inphp\Core\Modules;
use Inphp\Core\Object\Message;
use Inphp\Core\Services\Http\Session;
use Inphp\Core\Util\Str;

class auth
{
    public function index(): Message
    {
        //超限检测、IP禁止检测
        $limit = Session::get("loginTimes", 0);
        if ($limit == 1 || checkIPDisable()) {
            return httpMessage(34);
        }

        //
        $username = POST("username");
        $username = !empty($username) ? Str::trim($username) : null;
        if (empty($username)) {
            return httpMessage("缺少用户名");
        }
        if (strlen($username) < 6) {
            return httpMessage("用户名无效");
        }

        $password = POST("password");
        if (empty($password)) {
            return httpMessage("缺少密码");
        }
        if (strlen($password) < 6) {
            return httpMessage("密码无效");
        }

        //校验
        $adminConfig = Modules::getModule("admin")->getConfig();
        $adminConfig = is_array($adminConfig) ? $adminConfig : [];
        $auth = $adminConfig["auth"] ?? [];
        $auth = is_array($auth) ? $auth : [];
        //用户名判断
        $authUsername = $auth["username"] ?? null;
        if ($authUsername != $username) {
            return httpMessage(32);
        }
        //密码判断
        $pwdKey = $auth["pwdKey"] ?? "";
        $pwd = $auth["password"] ?? "";
        if (md5(md5($password).$pwdKey) === $pwd) {
            //生成负数的UID
            $uid = 0 - mt_rand(100, 9999);
            //生成TOKEN
            $token = hash_hmac("md5", time()."&".$uid, getIP());
            $token = strtoupper($token);
            //生成新的账户缓存
            $newAuth = $auth;
            $newAuth["uid"] = $uid;
            $adminConfig["auth"] = $newAuth;
            if (!Modules::getModule("admin")->saveConfig("config", $adminConfig)) {
                return httpMessage("无法保存到缓存，请检测写入权限");
            }
            //保存到缓存， 超级管理员，默认有效时长为1小时
            $adminLifeTime = $auth["lifeTime"] ?? 3600;
            $adminLifeTime = is_numeric($adminLifeTime) && $adminLifeTime >= 3600 ? $adminLifeTime : 3600;
            $adminLifeTime = min($adminLifeTime, 86400);
            Redis::set("Token_{$token}", $uid, $adminLifeTime);
            //超级管理员账户授权，使用 session
            Session::set("token", $token);
            return httpMessage(0, "success");
        }
        return httpMessage(32);
    }
}